package action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.BigClass;
import model.Commodity;
import model.Notice;
import model.ShoppingCar;
import model.User;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.junit.Test;

import daoJDBC.interfaceDO.serviceDO.Do_IDUS;

public class QianServlet extends HttpServlet{

	//创建操作数据库的对象
	Do_IDUS idus=new Do_IDUS();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取前台传过来的操作意向
		String option=req.getParameter("option");
		if (option!=null) {
			if (option.equals("login")) {
				login(req,resp);
			}else if (option.equals("sel_a")) {
				selectall(req,resp);
			}else if (option.equals("sel_o")) {
				selectone(req,resp);
			}else if (option.equals("addsc")) {
				addsc(req,resp);
			}else if (option.equals("selsc")) {
				selsc(req,resp);
			}else if (option.equals("delsc")) {
				delsc(req,resp);
			}else if (option.equals("register")) {
				register(req,resp);
			}else if (option.equals("updsc")) {
				updsc(req,resp);
			}else if (option.equals("selindex")){
				selindex(req,resp);
			}else if (option.equals("getout")){
				getout(req,resp);
			}else {
				selindex(req,resp);
			}
		}
	}
	
	public void getout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----退出登陆--");
		req.getSession().removeAttribute("listuser");
		resp.sendRedirect("qiantai/login.jsp");
	}
	
	public void selectone(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----selectone----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		HttpSession sess=req.getSession();
		sess.removeAttribute("list_commodity");
		String ta_name=req.getParameter("ta");
		int thisID=Integer.parseInt(req.getParameter("thisID"));
		if (ta_name.equals("commodity")) {
			List list_commodity=idus.selectOne(ta_name, thisID);
			sess.setAttribute("list_commodity", list_commodity);
			System.out.println(">>>集合大小>>>"+list_commodity.size());
			resp.sendRedirect("qiantai/info.jsp");
		}else if (ta_name.equals("notice")) {
			List list_notice=idus.selectOne(ta_name, thisID);
			sess.setAttribute("list_notice", list_notice);
			System.out.println(">>>集合大小>>>"+list_notice.size());
			Notice no=(Notice)list_notice.get(0);
			String s=no.getId()+"---"+no.getNoticeTitle()+"---"+no.getNoticeContent();
			System.out.println(s);
			resp.sendRedirect("qiantai/notice_content.jsp");
		}
	}
	//查找小分类中的所有商品
	public void selectall(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----selectall----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		HttpSession sess=req.getSession();
		String smallclassID=req.getParameter("smallclassID");
		String sql="select * from smallclass where id=?";
		System.out.println(">>>>>小分类>>>"+smallclassID);
		Object []obj=new Object[]{smallclassID};
		idus.dosql(sql, obj);
		ResultSet rs=idus.getRS();
		if (rs!=null) {
			try {
				rs.next();
				String s_c_Name=rs.getString("smallclassName");
				List list_commodity=idus.selectComm(2,s_c_Name);
				sess.setAttribute("list_commodity", list_commodity);
//				sess.setAttribute("s_c_Name", s_c_Name);
				System.out.println(">>>>>小分类>>>"+s_c_Name);
				resp.sendRedirect("qiantai/catlist.jsp");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	//主页查询
	public void selindex(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----selindex----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		List list_big=idus.select("bigclass", 0);
		BigClass b=(BigClass) list_big.get(0);
		System.out.println("-----测----"+b.getBigclassName());
		List list_small=idus.select("smallclass", 0);
		List list_commodity=idus.select("commodity", 0);
		List list_notice=idus.select("notice", 0);
		List list_newcommodity=idus.selectComm(1, "Y");
		HttpSession sess=req.getSession();
		sess.setAttribute("list_big", list_big);
		sess.setAttribute("list_small", list_small);
		sess.setAttribute("list_commodity", list_commodity);
		sess.setAttribute("list_notice", list_notice);
		sess.setAttribute("list_newcommodity", list_newcommodity);
		resp.sendRedirect("qiantai/index.jsp");
	}

	//删除购物车内的商品信息
	public void delsc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----delsc----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		int id=Integer.parseInt(req.getParameter("thisID"));
		System.out.println("thisID>>>>>"+id);
		int i=idus.delete("shoppingcar", id);
		if (i>0) {
			System.out.println("删除购物车商品成功");
			resp.sendRedirect("QianServlet?option=selsc");//跳转购物车
		}else {
			System.out.println("删除失败");resp.sendRedirect("QianServlet?option=selsc");//跳转购物车
		}
	}

	//修改购物车内商品信息
	public void updsc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----updsc----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		int thisID=Integer.parseInt(req.getParameter("thisID"));
		int saleNum=Integer.parseInt(req.getParameter("saleNum"));
		String sql="update shoppingcar set saleNum=? where id=?";
		int i=idus.update(sql, new Object[]{saleNum,thisID});
		if (i>0) {
			System.out.println("购物车数据修改成功--");
			selsc(req, resp);
		}else {
			System.out.println("数据修改失败");selsc(req, resp);
		}
		
	}

	//查询购物车所有的商品
	public void selsc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----selsc----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		HttpSession sess=req.getSession();
		if(sess.getAttribute("account")!=null){
		List list=idus.selectSC();
		if (list!=null&&list.size()!=0) {
			sess.setAttribute("list", list);
			double amountnum=0,oldallnum=0;
			for (Object obj : list) {
				ShoppingCar sc=(ShoppingCar)obj;
				amountnum+=(sc.getSale()*sc.getSaleNum());//总金额，即购物车所有商品总价
				oldallnum+=(sc.getOldSale()*sc.getSaleNum());//原价总和
			}
			double yhj=oldallnum-amountnum;
			DecimalFormat df=new DecimalFormat("#0.0");
			Double amount=Double.parseDouble(df.format(amountnum));
			System.out.println("---->>总价>>"+amount);
			Double youhui=Double.parseDouble(df.format(yhj));
			System.out.println("---->>优惠>>"+youhui);
			sess.setAttribute("amount", amount);
			sess.setAttribute("youhui", youhui);
			System.out.println("---->>>----");
			resp.sendRedirect("qiantai/buy.jsp");
		}else {
			System.out.println("购物为空----");
			sess.removeAttribute("list");
			resp.sendRedirect("qiantai/buy.jsp");
		}}else{
			resp.sendRedirect("qiantai/login.jsp");
		}
		
	}

	//往购物车添加商品
	public void addsc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----addsc----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		int thisID=Integer.parseInt(req.getParameter("comID"));
		List list=idus.selectOne("commodity", thisID);
		Commodity comm=(Commodity)list.get(0);
		String commodityName=comm.getCommodityName();
		System.out.println("---商品名>>>>"+commodityName);
		double oldSale=comm.getOldSale();
		System.out.println("---oldSale>>>>"+oldSale);
		double sale=comm.getSale();
		System.out.println("---sale>>>>"+sale);
		Double zekou=(sale/oldSale)*10;
		System.out.println("---zekou>>>>"+zekou);
		int saleNum=1;
		String sql="insert into shoppingcar(commodityName,oldSale,sale,zekou,saleNum) values(?,?,?,?,?)";
		int i=idus.insert(sql, new Object[]{commodityName,oldSale,sale,zekou,saleNum});
		if (i>0) {
			System.out.println("商品成功添加进购物车---");
			resp.sendRedirect("QianServlet?option=selsc");//跳转购物车
		}else {
			System.out.println("商品添加失败");
			resp.sendRedirect("QianServlet?option=selsc");//跳转购物车
		}
	}

	/**
	 * 用户登陆
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws SQLException 
	 * @throws SQLException 
	 */
	public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		// TODO Auto-generated method stub
		System.out.println("----login----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		String ta_name=req.getParameter("ta");
		String account=req.getParameter("acc");
		String password=req.getParameter("pwd");
		ResultSet rs=idus.enterSelect(ta_name, account, password);
		List list=new ArrayList();
		if (rs!=null) {
			try {
				while(rs.next()){
					String name=rs.getString("name");
					String cellphone=rs.getString("cellphone");
					String address=rs.getString("address");
					list.add(new User(account, name, cellphone, address));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			HttpSession sess=req.getSession();
			System.out.println("用户登陆成功--跳转success页面");
			sess.setAttribute("listuser", list);
			sess.setAttribute("account", account);
			System.out.println("用户帐号名为》》"+account);
			resp.sendRedirect("qiantai/login_success.jsp");
			pw.println(account);
		}else {
			req.getSession().setAttribute("dlsb", "用户名或密码错误");
			resp.sendRedirect("qiantai/login.jsp");
		}idus.toClose();
	}
	@Test
	public void test(){
		Map map=new HashMap();
		map.put("a", "aaa");
		String a1=(String)map.get("a");
		System.out.println(a1);
		Date date=new Date();
		
		System.out.println(new Date().toString());
	}
	/**
	 * 用户注册
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----register----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		//创建工厂对象
		DiskFileItemFactory factory=new DiskFileItemFactory();
		//创建解析对象
		ServletFileUpload sfu=new ServletFileUpload(factory);
		//解析请求
		Map map=new HashMap();		
		try {
			List list = sfu.parseRequest(req);
			
			for (int i = 0; i < list.size(); i++) {
				FileItem file=(FileItem)list.get(i);
				if (file.isFormField()) {//判断获得的表单文件是否是普通文本
					String name=file.getFieldName();//获取name的值
					String value=file.getString("utf-8");//获取表单中的value值，加字符编码是为了防止乱码
					System.out.println(name+"----"+value);
					map.put(name, value);//存入MAP集合中
				}else {//不是普通文本说明是上传文件 ，上传文件用另一种获取方式 
					String name=file.getFieldName();//同样是获取name的值 
					String fileName=file.getName();//获取上传的文件的文件名
					System.out.println(name+"----"+fileName);//查看一下上传的文件 名
					if (!fileName.equals("")) {//文件名不为空则保存文件 
						String path=getServletContext().getRealPath("touxiang");//获得文件的保存路径
						System.out.println(path);//文件的保存路径
						String imgName=UUID.randomUUID().toString()+"_"+fileName;
						System.out.println(imgName);
						file.write(new File(path, imgName));
						String image="touxiang\\"+imgName;
						map.put(name, image);
					}	
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String fname=(String)map.get("fname");
		String lname=(String)map.get("lname");
		String name=fname+lname;//name值
		/*name*/System.out.println("--name>>"+name);
		String account=(String)map.get("sname");
		/*account*/System.out.println("--account>>"+account);
		String password=(String)map.get("pass");
		/*password*/System.out.println("--password>>"+password);
		String email=(String)map.get("email");
		/*email*/System.out.println("--email>>"+email);
		String sex=(String)map.get("gender");
		/*sex*/System.out.println("--sex>>"+sex);
		String touxiang=(String)map.get("touxiang");
		/*touxiang*/System.out.println("--touxiang>>"+touxiang);
		String hobby=(String)map.get("hobby");
		/*hobby*/System.out.println("--hobby>>"+hobby);
		String year=(String)map.get("nYear");
		String month=(String)map.get("nMonth");
		String day=(String)map.get("nDay");
		String birth=year+"年"+month+"月"+day+"日";//birth值
		/*birth*/System.out.println("--birth>>"+birth);
		String sql="insert into user(account,name,password,email,sex,touxiang,hobby,birth) values(?,?,?,?,?,?,?,?)";
		int i=idus.insert(sql, new Object[]{account,name,password,email,sex,touxiang,hobby,birth});
		if (i>0) {
			System.out.println("--注册成功--");
			List list=new ArrayList();
			User user=new User();
			user.setAccount(account);
			user.setName(name);
			list.add(user);
			req.getSession().setAttribute("listuser", list);
			req.getSession().setAttribute("account", account);
			System.out.println("用户帐号名为》》"+account);
			resp.sendRedirect("qiantai/register_success.html");
		}else {
			pw.println("注册失败--");
			resp.sendRedirect("qiantai/register.html");
		}
	}
}
